

export default function Model(Req, opts) {
  return {
    cancel () {
      if (this.controller) {
        this.controller.abort()
      }
    },
    async send(data, params) {
      if (!!globalThis.location) this.controller = new AbortController()
      else this.controller = null
      const rurl = Req.getRealUrl(opts)
      const method = opts.method || 'get'
      const flag = method.toLowerCase() + rurl
      const index = Req.networkList.findIndex(r => r === flag)
      // 防重
      if (!opts.canRepeat && index > -1) {
        const response = { code: -999, msg: '请不要重复请求！' }
        Req.handleError(response)
        return
      }
      opts.params = params
      opts.data = data
      if (method === 'get') {
        !params && (opts.params = data)
        delete opts.data
      }
      try {
        Req.networkList.push(flag)
        const response = await Req.request({
          ...opts,
          signal: this.controller && this.controller.signal
        })
        return await Req.handleBack(response)
      } catch (error) {
        Req.handleError(error)
        return
      } finally {
        // 标记结束
        const { method = 'get', url, prefix } = opts
        Req.handleFinally({ method, url, prefix })
      }
    }
  }
}
